//创建websocket服务器
const websocket = require("ws")
const app = require("./node服务器")

let port = 6060;
const wss = new websocket.Server({ port: port }); //创建websocket服务器
let clients = new Set(); // 存放所有客户端
var userAndOther = {};

app.post("/login",function(req,res){
    let {username,Receiver} = req.body;
    if(username && Receiver){
        userAndOther = req.body
    }
    res.send({code:200,msg:"登录成功",data:username})
})

//登录成功之后链接ws服务器
wss.on("connection", (ws) => {
    // 去重
    for (const item of clients) {
        if (item.username == userAndOther.username) {
            console.log("已删除" + item.username);
            clients.delete(item);
            break
        }
    }
    clients.add(Object.assign(ws, userAndOther));
    console.log(clients.size + " 人在线");
    ws.on("message", (msg) => {
        let data = JSON.parse(msg);
        console.log(data);
        Array.from(clients).forEach((item) => {
            if (item.username == data.username || item.username == data.Receiver) {
                item.send(JSON.stringify(Object.assign(data,{time:new Date().getFullYear() + "" + new Date().toLocaleString()})));
            }
        })
    })
})

